<template>
  <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="0px"
    :inline-message="true">
    <el-table border :data="formData" :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }">
      <el-table-column label="序号" type="index" width="100" align="center" />
      <el-table-column label="审核项" align="center">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.name`" :rules="formRules.name" class="mb-0px!">
            <el-input type="textarea" v-model="row.name" placeholder="请输入" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="100">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加审核项</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { AuditTypeApi } from '@/api/business/audittype'

const props = defineProps<{
  auditTypeId: number // 分类（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  auditTypeId: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

console.log("props.auditTypeId", props.auditTypeId);


/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.auditTypeId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await AuditTypeApi.getAuditConfigListByAuditTypeId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    auditTypeId: undefined,
    name: undefined,
    description: undefined
  }
  row.auditTypeId = props.auditTypeId as any
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

const cleanData = () => {
  //清空数据
  formData.value = []
}

defineExpose({ validate, getData, cleanData })
</script>
